const app = getApp()

Page({
  data: {
    scanResult: '',
    type: 'inbound' // inbound 或 outbound
  },

  onLoad(options) {
    this.setData({
      type: options.type || 'inbound'
    })
  },

  handleScanCode(e) {
    const result = e.detail.result
    this.setData({
      scanResult: result
    })
  },

  handleCancel() {
    this.setData({
      scanResult: ''
    })
  },

  handleConfirm() {
    const { scanResult, type } = this.data
    if (!scanResult) {
      wx.showToast({
        title: '请先扫描设备',
        icon: 'none'
      })
      return
    }

    if (type === 'inbound') {
      // 入库需要填写额外信息
      wx.navigateTo({
        url: `/pages/info/info?deviceId=${scanResult}&type=inbound`
      })
    } else {
      // 出库直接保存
      this.saveOutboundRecord(scanResult)
    }
  },

  saveOutboundRecord(deviceId) {
    const today = new Date()
    const date = today.toISOString().split('T')[0]
    
    const record = {
      deviceId,
      date,
      type: 'outbound'
    }

    // 保存到本地存储
    const records = wx.getStorageSync(app.globalData.storageKey) || []
    records.push(record)
    wx.setStorageSync(app.globalData.storageKey, records)

    // 生成CSV文件
    this.generateCSV(records, 'outbound')

    wx.showToast({
      title: '出库成功',
      icon: 'success',
      duration: 2000,
      success: () => {
        setTimeout(() => {
          wx.navigateBack()
        }, 2000)
      }
    })
  },

  generateCSV(records, type) {
    const today = new Date()
    const dateStr = today.toISOString().slice(0, 10).replace(/-/g, '')
    const fileName = `${type === 'inbound' ? '入库记录' : '出库记录'}_${dateStr}.csv`

    let csvContent = type === 'inbound' 
      ? '设备号,日期,来源,数量\n'
      : '设备号,日期\n'

    records.forEach(record => {
      if (record.type === type) {
        if (type === 'inbound') {
          csvContent += `${record.deviceId},${record.date},${record.source},${record.quantity}\n`
        } else {
          csvContent += `${record.deviceId},${record.date}\n`
        }
      }
    })

    const fs = wx.getFileSystemManager()
    fs.writeFile({
      filePath: `${wx.env.USER_DATA_PATH}/${fileName}`,
      data: csvContent,
      encoding: 'utf8',
      success: () => {
        console.log('CSV文件生成成功')
      },
      fail: (err) => {
        console.error('CSV文件生成失败', err)
        wx.showToast({
          title: '文件保存失败',
          icon: 'none'
        })
      }
    })
  }
}) 